﻿@{
    ViewBag.Title = "Card Products";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/css/product.css" rel="stylesheet" />
<style>
    form label {
        font-weight: bold;
    }
</style>

<table id="marbleTable" class="stripe row-border order-column">
    <thead>
        <th>ID</th>
        <th></th>
        <th>Name</th>
        <th>Type</th>
        <th>Category</th>
        <th>POSCounter</th>
        <th>Active</th>
        <th>DisplayInPOS</th>
        <th>DisplayGroup</th>
        <th>AutoGenerateCardNumber</th>
        <th>OnlyVIP</th>
        <th>Price</th>
        <th>FaceValue</th>
        <th>TaxInclusive</th>
        <th>TaxPercent</th>
        <th>Tax</th>
        <th>FinalPrice</th>
        <th>EffectivePrice</th>
        <th>LastUpdatedBy</th>
        <th>LastUpdatedDate</th>
    </thead>
    <tbody>
        @{
            var count = 0;
        }
        @foreach (var item in ViewBag.productDetails)
        {
            count++;
            <tr id="@count">
                <td>
                    <lable class="fixedCol1">@(item.Id == 0 ? "" : item.Id) </lable>
                </td>
                <td>
                    @if(item.Id > 0) {
                    <a class="edit" title="Edit" data-toggle="tooltip" onclick="EditProduct('@item.Id')">
                        <i class="material-icons" style="cursor: pointer;">&#xE254;</i>
                    </a>
                    <a class="delete" title="Delete" data-toggle="tooltip" onclick="DeleteProduct('@item.Id')">
                        <i class="material-icons" style="cursor: pointer;">&#xE872;</i>
                    </a>
                    }
                </td>
                <td>
                    <input type="text" class="fixedCol3" value="@item.Name"/>
                </td>
                <td>
                    <select name="TypeList" id="TypeList">
                        @foreach (var dow in (List<Marbale.BusinessObject.IdValue>)Session["TypeList"])
                        {
                            if (@item.Type == (@dow.Id).ToString())
                            {
                            <option value="@dow.Value" id="@dow.Id" selected>@dow.Value</option>
                            }
                            else
                            {
                            <option value="@dow.Value" id="@dow.Id">@dow.Value</option>
                            }
                        }
                    </select>
                </td>
                <td>
                    <select name="categoryList" id="categoryList">
                        @foreach (var dow in @item.CategoryList)
                        {
                            if (@dow.Id != null && @item.Category == (@dow.Id).ToString())
                            {
                            <option value="@dow.Value" id="@dow.Id"  selected>@dow.Value</option>
                            }
                            else
                            {
                            <option value="@dow.Value" id="@dow.Id" >@dow.Value</option>
                            }
                        }
                    </select>
                </td>
                <td>
                    <input type="text" value="@item.POSCounter" />
                </td>
                <td>
                    <input type="checkbox"  @(item.Active ? "checked='checked'" : "") value="@item.Active" />
                </td>
                <td>
                    <input type="checkbox"  @(item.DisplayInPOS ? "checked='checked'" : "") value="@item.DisplayInPOS" />
                </td>
                <td>
                    <select name="displayGroupList" id="displayGroupList">
                        @foreach (var dow in (@item.DisplayGroupList))
                        {
                            if (@item.DisplayGroupId == (@dow.Id))
                            {
                            <option value="@dow.Value" id="@dow.Id"  selected>@dow.Value</option>
                            }
                            else
                            {
                            <option value="@dow.Value" id="@dow.Id" >@dow.Value</option>
                            }
                        }
                    </select>
                </td>
                <td>
                    <input type="checkbox"  @(item.AutoGenerateCardNumber ? "checked='checked'" : "") value="@item.AutoGenerateCardNumber"/>
                </td>
                <td>
                    <input type="checkbox" @(item.OnlyVIP ? "checked='checked'" : "") value="@item.OnlyVIP" />
                </td>
                <td>
                    <input type="text" value="@item.Price" id="Price@(count)" />
                </td>
                <td>
                    <input type="text" value="@item.FaceValue" id="FaceValue@(count)" />
                </td>
                <td>
                    <input type="checkbox" @(item.TaxInclusive ? "checked='checked'" : "") value="@item.TaxInclusive" id="TaxInclusive@(count)"  />
                </td>
                <td>
                    <input type="text" value="@item.TaxPercentage" id="TaxPercentage@(count)"/>
                </td>
                <td>
                    <select name="taxlist" id="taxlist">
                        @foreach (var dow in (List<Marbale.BusinessObject.Tax.TaxSet>)Session["TaxList"])
                        {
                            if (@item.TaxId == (@dow.Id))
                            {
                            <option value="@dow.Value" id="@dow.Id"  selected>@dow.Value</option>
                            }
                            else
                            {
                            <option value="@dow.Value" id="@dow.Id" >@dow.Value</option>
                            }
                        }
                    </select>
                </td>
                <td>
                    <input type="text" id="FinalPrice@(count)"  value="@item.FinalPrice" />
                </td>
                <td>
                    <input type="text" value="@item.EffectivePrice" id="EffectivePrice@(count)" />
                </td>
                <td>
                    <input type="text" value="@item.LastUpdatedBy"  disabled/>
                </td>
                <td>
                    <input type="text" value="@item.LastUpdatedDate" disabled/>
                </td>
            </tr> 
        }
    </tbody>
</table>
<div class="action">
    <button class="btn btn-primary btn-md" role="button" onclick="history.back();" id="back">Back</button>
    <button class="btn btn-primary btn-md" role="button" onclick="SaveProducts()" disabled id="saveproduct">Save</button>
    <button id="addRow" class="btn btn-primary btn-md" role="button">Add</button>
    <button type="button" class="btn btn-primary" data-toggle="modal" onclick="EditProduct(0)">
        New
    </button>
    <a href="/Marble/index" class="btn btn-primary">Close</a>
</div>
<script>
    var updatedArray = [];
    function UpdatedList(index) {
        if (!updatedArray.includes(index)) {
            updatedArray.push(index);
        }
    }

    $(document).on('change', '#taxlist', function () {
        debugger;
        var rowid = $(this).closest('tr').attr('id');
        var TaxId = $(this).find('option:selected').attr('id');
        //TaxId = $('#taxlist' + rowid + ' option:selected').val();

        var Price = $('#Price' + rowid).val();
        if (Price == "") {
            Price = null;
        }
        var FaceValue = Number($('#FaceValue' + rowid).val());
        taxinclusive = $('#TaxInclusive' + rowid).is(":checked");
        var model = {
            Id: TaxId,
            Price: Price,
            FaceValue: FaceValue,
            TaxInclusive: taxinclusive
        };
        if (TaxId == "") {
            $('#EffectivePrice' + rowid).val(Price);
            $('#FinalPrice' + rowid).val(Price);
        }
            //JSON.stringify({ TaxId: TaxId, Price: Price, TaxInclusive: taxinclusive, FaceValue: FaceValue }),
        else {

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("TaxDetails", "Product")',
                data: JSON.stringify({ model: model }),
                dataType: "json",
                success: function (data) {
                    $('#EffectivePrice' + rowid).val(data.EffectivePrice);
                    $('#TaxPercentage' + rowid).val(data.Taxpercent);
                    $('#FinalPrice' + rowid).val(data.FinalPrice);
                },
                error: function (e) {
                    alert(e);
                }
            });
        }
    });
    $(document).ready(function () {
        var table = $('#marbleTable').DataTable({
            scrollY: "400px",
            scrollX: true,
            scrollCollapse: true,
            editable: true,
            stateSave: true,
            // paging: true,
            bPaginate: false,
            bInfo: false,
            bFilter: false,
            bSort: false,
            "createdRow": function (row, data, index) {
                $('td', row).addClass('tblRow');
            },
            rowCallback: function (row, data) {
                debugger;
                var element = $('td', row);
                element.on("change", function (e) {
                    UpdatedList($(this).parent().index());
                });
            },
            //order: [[ 0, "desc" ]],
            fixedColumns: {
                leftColumns: 3
            }
        });
        var counter = 1;

        $('#addRow').on('click', function () {
            $("#saveproduct").attr("disabled", false);
            var fixedcolumn1values = $('.DTFC_Cloned lable.fixedCol1');
            var fixedcolumn3values = $('.DTFC_Cloned input.fixedCol3');

            var typeListOptions = '';
              @foreach (var dow in (List<Marbale.BusinessObject.IdValue>)Session["TypeList"])
              {
                 @: typeListOptions = typeListOptions + '<option id="@dow.Id" value="" >@dow.Value</option>';
                          }
            var taxListOptions = '';
              @foreach (var dow in (List<Marbale.BusinessObject.Tax.TaxSet>)Session["TaxList"])
              {
                 @: taxListOptions = taxListOptions + '<option id="@dow.Id" value="" >@dow.Value</option>';
              }
            taxListOptions = taxListOptions + '</select>';
            var categoryListOptions = '';
              @foreach (var dow in (List<Marbale.BusinessObject.IdValue>)Session["CategoryList"])
              {
                   @: categoryListOptions = categoryListOptions + '<option id="@dow.Id" value="" >@dow.Value</option>';
              }
            categoryListOptions = categoryListOptions + ' </select>';

            var displayGroupListOptions = '';
              @foreach (var dow in (List<Marbale.BusinessObject.IdValue>)Session["DisplayGroupList"])
              {
                   @: displayGroupListOptions = displayGroupListOptions + '<option id="@dow.Id" value="" >@dow.Value</option>';
              }
            displayGroupListOptions = displayGroupListOptions + ' </select>';

            table.row.add([
                '<lable class="fixedCol1"></lable>',
                '',
                '<input class="fixedCol3" type="text" value="" />',
                '<select name="TypeList" id="TypeList">' + typeListOptions,
                '<select name="categoryList" id="categoryList">' + categoryListOptions,
                '<input type="text" value="" />',
                '<input type="checkbox" />',
                '<input type="checkbox" />',
                '<select name="displayGroupList" id="displayGroupList">' + displayGroupListOptions,
                '<input type="checkbox" />',
                '<input type="checkbox" />',
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<input type="checkbox" />',
                '<input type="text" value="" />',
                '<select name="taxlist" id="taxlist">' + taxListOptions,
                '<input type="text" value="" />',
                '<input type="text" value="" />',
                '<input type="text" value="" disabled/>',
                '<input type="text" value="" disabled/>',
            ]).draw(false);

            for (var i = 0, j = fixedcolumn1values.length; i < j; i++) {
                $('.DTFC_Cloned lable.fixedCol1')[i].innerHTML = fixedcolumn1values[i].innerHTML;
            }
            for (var i = 0, j = fixedcolumn3values.length; i < j; i++) {
                $('.DTFC_Cloned input.fixedCol3')[i].value = fixedcolumn3values[i].value;
            }
        });
        $(".tblRow").on("change", function (e) { UpdatedList($(this).parent().index()); });
    });
    function SaveProducts() {
        if (updatedArray.length > 0) {
            var items = [];
            var table = document.getElementById('marbleTable');
            var fixedcolumn1 = $('.DTFC_Cloned lable.fixedCol1');
            var fixedcolumn3 = $('.DTFC_Cloned input.fixedCol3');

            for (var r = 0, n = table.rows.length; r < n; r++) {
                if (updatedArray.includes(r)) {
                    var rowIndex = r + 1;
                    if (fixedcolumn3[r].value.trim() == '') {
                        alert('Please Enter Product Name');
                        return false;
                    }
                    if (table.rows[rowIndex].cells[11].children[0].value == '') {
                        alert('Please Enter Price');
                        return false;
                    }
                    var selectedTypeIndex = table.rows[rowIndex].cells[3].children[0].options["selectedIndex"];
                    var selectedCategoryIndex = table.rows[rowIndex].cells[4].children[0].options["selectedIndex"];
                    var selectedDisplayGroupIndex = table.rows[rowIndex].cells[8].children[0].options["selectedIndex"];
                    var selectedTaxIndex = table.rows[rowIndex].cells[15].children[0].options["selectedIndex"];
                    items.push({
                        Id: fixedcolumn1[r].innerHTML,
                        Name: fixedcolumn3[r].value,
                        Type: table.rows[rowIndex].cells[3].children[0].options[selectedTypeIndex].id,
                        Category: table.rows[rowIndex].cells[4].children[0].options[selectedCategoryIndex].id,
                        POSCounter: table.rows[rowIndex].cells[5].children[0].value,
                        Active: table.rows[rowIndex].cells[6].children[0].checked,
                        DisplayInPOS: table.rows[rowIndex].cells[7].children[0].checked,
                        DisplayGroupId: table.rows[rowIndex].cells[8].children[0].options[selectedDisplayGroupIndex].id,
                        AutoGenerateCardNumber: table.rows[rowIndex].cells[9].children[0].checked,
                        OnlyVIP: table.rows[rowIndex].cells[10].children[0].checked,
                        Price: table.rows[rowIndex].cells[11].children[0].value,
                        FaceValue: table.rows[rowIndex].cells[12].children[0].value,
                        TaxInclusive: table.rows[rowIndex].cells[13].children[0].checked,
                        Taxpercent: table.rows[rowIndex].cells[14].children[0].value,
                        TaxId: table.rows[rowIndex].cells[15].children[0].options[selectedTaxIndex].id,
                        FinalPrice: table.rows[rowIndex].cells[16].children[0].value,
                        EffectivePrice: table.rows[rowIndex].cells[17].children[0].value,
                        ExpiryDate: '10/10/2020',
                        StartDate: '10/10/2020'
                    });
                }
            }

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '@Url.Action("UpdateProducts", "product")',
                data: JSON.stringify({ products: items }),
                dataType: "json",
                success: function (data) {
                    alert('Data Saved');
                    location.reload();
                },
                error: function (e) {
                    alert(e);
                }
            });
        }
    }
    $(document).ready(function () {
        $('.dropdown-toggle').collapse({
            toggle: false
        });
    });
    $('.close').click(function () {
        location.reload();
    });
    $(':input').on('change', function () {
        $("#saveproduct").attr("disabled", false);
    });

    $("#newproductmodel").draggable({
        handle: ".modal-header"
    });

    function EditProduct(id) {
        $('#myModal').modal('show');
        $('#modelBody').css({
            'left': '-40%',
            'width': 1000
        });
        if (id != 0) {
            $('#modelBody').load('/Product/Edit', { "id": id });
            $('.modal-title').text('Edit Product');
        } else {
            $('#modelBody').load('/Product/Edit');
            $('.modal-title').text('New Product');
        }
    }
    function DeleteProduct(id) {
        if (id != 0) {
            if (confirm('Are you sure you want to delete this from database?')) {
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("DeleteProduct", "Product")',
                    data: { Id: id },
                    dataType: "json",
                    success: function (data) {
                        location.reload();
                    },
                    error: function (e) {
                        alert(e);
                    }
                });
            }

        }
    }

</script>
